package com.tang.module.useapi.module.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tang.common.constant.UniversalConstant;
import com.tang.common.exception.GlobalException;
import com.tang.common.utils.HttpRequestBaseUtil;
import com.tang.module.useapi.module.entity.IpLocation;
import com.tang.module.useapi.entity.UseApiParam;
import com.tang.module.useapi.entity.UseApiSupplier;
import com.tang.module.useapi.mapper.UseApiParamMapper;

import com.tang.module.useapi.mapper.UseApiSupplierMapper;
import com.tang.module.useapi.module.service.BasicUseApi;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.tang.common.constant.UseParamConstant.*;

/**
 * 高德基础api
 * @author tang
 * @date 2022/2/14 15:08
 */
@Service
public class GaoDeBasicUseApi implements BasicUseApi {

    @Resource
    private UseApiParamMapper useApiParamMapper;

    @Resource
    private UseApiSupplierMapper useApiSupplierMapper;


    @Override
    public IpLocation byIpGetLocation(String ip) {
        //获得API对应的厂商
        UseApiSupplier useApiSupplier = useApiSupplierMapper.selectOne(Wrappers.<UseApiSupplier>lambdaQuery().select(UseApiSupplier::getId).eq(UseApiSupplier::getCreditCode, GAO_DE_CREDIT_CODE));
        if (useApiSupplier == null){
            throw new GlobalException("无法通过供应商社会信用代码获取供应商数据");
        }
        //获得定义的供应商参数
        List<UseApiParam> paramList = useApiParamMapper.selectList(Wrappers.<UseApiParam>lambdaQuery().eq(UseApiParam::getSupplierId, useApiSupplier.getId()));
        //获得供应商参数map
        Map<String, String> paramMap = paramList.parallelStream().collect(Collectors.toMap(UseApiParam::getParamKey, UseApiParam::getParamValue));
        Map<String, String> requestMap = new HashMap<>();
        requestMap.put("key",paramMap.get(APP_KEY_WEB));
        requestMap.put("type","4");
        requestMap.put("ip",ip);
        //开始请求
        Map<String, String> map = HttpRequestBaseUtil.get(
                paramMap.get(IP_ADDRESS_URL), requestMap, Map.class, null,"IP定位");
        //status为0说明请求失败
        if (UniversalConstant.ZERO.equals(map.get(UniversalConstant.STATUS))) {
            throw new GlobalException("高德请求ip定位失败，失败原因: " + map.get("info"));
        }
        return JSON.parseObject(JSON.toJSONString(map),IpLocation.class);
    }

}
